<template>
  <div>
    <div class="top-bar">
      <van-nav-bar title="发红包" left-arrow @click-left="onClickLeft" />
    </div>
    <div class="main">
      <!-- 金额输入 -->
      <div class="main_priceInput">
        <div class="priceInput">
          <div class="price_text">金额</div>
          <div class="price_box">
            <van-field
              @keyup="Price_keyup"
              v-model="Pricevalue"
              type="number"
              placeholder="填写金额"
            />
            <span style="font-size: 17px">元</span>
          </div>
        </div>
        <div class="Blessings">
          <van-field
            v-model="message"
            rows="2"
            autosize
            type="textarea"
            maxlength="20"
            placeholder="大吉大利，恭喜发财！"
          />
        </div>
        <div class="price_titel">
          <span>￥</span>
          <span>{{ price }}.00</span>
        </div>
        <div class="sendBox">
          <div class="send_btn">
            <van-button
              @click="openInputPassword"
              :disabled="btndisabled"
              color="linear-gradient(to right, #ff6034, #ee0a24)"
            >
              发红包
            </van-button>
          </div>
          <p>安全提示:红包无法用作交易凭证,购物请拍订单付款</p>
        </div>
      </div>
    </div>
    <!-- 支付选择 -->
    <van-popup
      :close-on-click-overlay="false"
      v-model="popupshow"
      position="bottom"
      :style="{ height: '50%' }"
    >
      <div class="coloicon" @click="popupclose"><van-icon name="cross" /></div>
      <div class="priceShow">
        <p>乐淘购现金红包</p>
        <div class="price_con">
          <span class="price_tip">￥</span>
          <span class="price_m">{{ Pricevalue }}.00</span>
        </div>
      </div>
      <div class="Options_info">
        <van-cell
          title="乐淘购账号"
          :value="$store.state.emailLogin[0].Account"
        />
        <van-cell is-link title="付款方式">
          <template #right-icon>
            <div class="Account_info">
              <van-icon
                style="font-size: 15px"
                name="https://storage.360buyimg.com/payment-assets/sdk/bank/POST.png"
              />
              <div>中国邮政银行储蓄卡(5978)</div>
              <van-icon name="arrow" />
            </div>
          </template>
        </van-cell>
      </div>
      <div class="bottom_btn">
        <van-button
          :loading="btnload"
          :loading-text="loadingtext"
          @click="Payment"
          type="primary"
          block
          >立即付款</van-button
        >
      </div>
    </van-popup>
    <!-- end支付选择 -->
    <!-- 密码输入框 -->
    <van-overlay z-index="9999" :show="passwordShow">
      <div class="passwordBox">
        <div class="close" @click="closepasswordShow">
          <van-icon name="close" />
        </div>
        <div class="title_top">
          <div class="title_tip">请输入支付密码</div>
          <div class="title_price">请付款{{ Pricevalue }}.00元</div>
        </div>
        <div class="password-inputbox">
          <van-password-input
            :error-info="errorInfo"
            :length="6"
            :value="password"
          />
        </div>
      </div>

      <!-- 数字键盘 -->
      <van-number-keyboard
        :maxlength="6"
        v-model="password"
        :show="showKeyboard"
      />
    </van-overlay>
    <!-- end密码输入框 -->
  </div>
</template>
<script>
import { mapState } from "vuex";
let Base64 = require("js-base64").Base64; //用于字符串编码 解码 用来存储表情

export default {
  data() {
    return {
      Pricevalue: "",
      message: "",
      btndisabled: true,
      price: "0",
      popupshow: false,
      btnload: false,
      passwordShow: false,
      password: "",
      showKeyboard: true,
      errorInfo: "",
      loadingtext: "身份验证中...",
    };
  },
  mounted() {
    this.socketApi.initWebSocket();
  },
  created() {
    this.popupshow = false;
  },
  computed: {
    ...mapState(["emailLogin"]),
    receiveid() {
      return this.$store.state.friID; //获取对方的id
    },
  },
  watch: {
    password(password) {
      if (password.length === 6) {
        this.loadingtext = "正在付款...";
        this.passwordShow = false;
        this.$toast.loading({
          message: "正在核对...",
          forbidClick: true,
          loadingType: "spinner",
        });
        setTimeout(() => {
          this.$toast.clear();
          this.getPwd();
        }, 1000);
      }
    },
  },
  methods: {
    popupclose() {
      this.$dialog
        .confirm({
          message: "是否放弃本次付款？",
          confirmButtonText: "继续付款",
          confirmButtonColor: "#5275fb",
          cancelButtonText: "放弃",
        })
        .then(() => {
          // on confirm
        })
        .catch(() => {
          this.popupshow = false;
          this.$toast({
            message: "支付取消。",
            position: "bottom",
          });
        });
    },
    onClickLeft() {
      this.$router.go(-1);
      this.Pricevalue = "";
      this.price = "0";
      this.btndisabled = true;
    },
    Price_keyup() {
      if (this.Pricevalue < 1) {
        this.price = "0";
        this.Pricevalue = "";
        this.btndisabled = true;
      } else {
        this.price = this.Pricevalue;
        this.btndisabled = false;
      }
    },
    //打开密码输入框 及支付方式选择
    openInputPassword() {
      this.$toast.loading({
        message: "请稍后...",
        forbidClick: true,
        loadingType: "spinner",
      });
      setTimeout(() => {
        this.$toast.clear();
        this.popupshow = true;
      }, 1000);
    },
    Payment() {
      this.btnload = true;
      setTimeout(() => {
        this.passwordShow = true;
      }, 1000);
    },
    closepasswordShow() {
      this.btnload = false;
      this.passwordShow = false;
      this.password = "";
    },
    GivereEnvelopes() {
      if (this.message === "") {
        this.message = "大吉大利,恭喜发财！";
      }
      let data = {
        id: this.emailLogin[0].userID,
        receive_id: this.receiveid,
        user: this.emailLogin[0].Nickname,
        userImage: this.emailLogin[0].userImg,
        dateTime: new Date(),
        msg: Base64.encode(this.message),
        red_amount: this.Pricevalue,
        isOpen: "false",
        msgType: 10, //代表红包消息
        textType: "红包",
      };
      let lastmsg = {
        dateTime: new Date(),
        msg: Base64.encode("[红包]"),
        receive_id: this.receiveid,
        uid: this.emailLogin[0].userID,
      };
      this.socketApi.handleSendMsg(data);
      this.$store.commit("setfriID", this.receiveid);
      this.$store.commit("setchatName", this.$store.state.chatName);
      this.addmsgImg(data, lastmsg);
      this.btndisabled = true;
      this.Pricevalue = "";
      this.message = "";
      this.price = "0";
      this.$router.push("/chatNew");
    },
    async getPwd() {
      const { data: res } = await this.$http.get("payPwd", {
        params: {
          pwd: this.password,
          userID: this.$store.state.emailLogin[0].userID,
        },
      });
      if (res.status === 202) {
        this.password = "";
        this.errorInfo = "支付密码不正确！";
        this.passwordShow = true;
      } else {
        this.loadingtext = "正在付款...";
        setTimeout(() => {
          this.$toast.clear();
          this.loadingtext = "付款成功";
          this.btnload = false;
          this.popupshow = false;
          this.password = "";
          this.ExcludingAmount(); //扣除该用户的 账户金额
          // console.log("dassd");
          //
        }, 1200);
      }
    },
    //扣除余额
    async ExcludingAmount() {
      const { data: price } = await this.$http.get("QueryAmount", {
        params: { uid: this.$store.state.emailLogin[0].userID },
      });

      if (this.Pricevalue > price.Amount.Account_balance) {
        this.$toast("您的余额不足！");
      } else {
        this.addConsumptionInfo();
        const { data: res } = await this.$http.post("ExcludingAmount", {
          price: this.Pricevalue,
          uid: this.$store.state.emailLogin[0].userID,
        });
        if (res.status === 200) {
          this.GivereEnvelopes();
        }
      }
    },
    //增加消费支出
    async addConsumptionInfo() {
      let data = {
        conType: "红包-消费",
        time: new Date(),
        Expenditure: this.Pricevalue,
        Benefit: 0,
        typeIcon:
          "https://sss-1306551685.cos.ap-guangzhou.myqcloud.com/MobileShop/zhichu_redbox.png",
        userID: this.emailLogin[0].userID,
      };
      const { data: res } = await this.$http.post("addConsumptionInfo", data);
      console.log(res);
    },
    //新增聊天记录
    async addmsgImg(obj, obj2) {
      //新增聊天记录
      const { data: res } = await this.$http.post("addPrivatechat", obj);
      const { data: res1 } = await this.$http.post("UpdateLatestMsg", obj2);
      console.log(res);
      console.log(res1);
    },
  },
};
</script>
<style lang="less" scoped>
.van-nav-bar {
  background-color: #dd594a;
}
.main {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #fff4ee;
  .main_priceInput {
    position: relative;
    top: 10.5vh;
    .priceInput {
      background-color: white;
      width: 100vw;
      height: 6.5vh;
      position: absolute;

      display: flex;
      align-items: center;
      justify-content: space-between;
      .price_text {
        margin-left: 4.5vw;
        font-size: 17px;
      }
      .price_box {
        margin-right: 4.5vw;
        display: flex;
        align-items: center;
        width: 105px;
      }
    }
    .Blessings {
      width: 100vw;
      height: 11vh;
      position: absolute;
      left: 0;
      top: 10.5vh;
    }
    .price_titel {
      position: absolute;
      width: 25.5vw;
      height: 4vh;
      line-height: 4vh;
      top: 28.3vh;
      left: 36.7vw;
      //   border: 1px solid;
      font-size: 1.875rem;
      text-align: center;
    }
    .sendBox {
      position: absolute;
      width: 80.2vw;
      height: 8.5vh;
      top: 37.8vh;
      left: 10vw;
      .send_btn {
        height: 6vh;
        button {
          width: 100%;
        }
      }
      p {
        position: absolute;
        top: 8vh;
        color: #b5b5b5;
        white-space: nowrap;
        left: -9px;
      }
    }
  }
}
.priceShow {
  position: absolute;
  left: 50%;
  top: 15%;
  transform: translate(-50%, 0%);
  text-align: center;
  p {
    text-align: center;
    font-size: 15px;
  }
  .price_con {
    margin-top: 15px;
    .price_tip {
      font-weight: 600;
      font-size: 18px;
    }
    .price_m {
      font-size: 28px;
      font-weight: 600;
    }
  }
}
.Options_info {
  position: absolute;
  top: 35%;
  width: 100%;
}
.Account_info {
  display: flex;
  align-items: center;
}
.bottom_btn {
  position: absolute;
  bottom: 20px;
  width: 90%;
  left: 5%;
}
.coloicon {
  position: absolute;
  top: 10px;
  left: 10px;
  i {
    font-size: 22px;
  }
}
.passwordBox {
  width: 300px;
  height: 200px;
  /* border: 1px solid; */
  background-color: white;
  left: 50%;
  top: 15%;
  position: absolute;
  border-radius: 14px;
  transform: translate(-50%, 0);
  .close {
    i {
      font-size: 22px;
      top: 10px;
      left: 10px;
    }
  }
  .title_top {
    position: absolute;
    left: 50%;
    top: 30%;
    transform: translate(-50%, -50%);
    text-align: center;
    div {
      margin: 6px;
    }
    .title_tip {
      font-size: 16px;
    }
  }
  .password-inputbox {
    position: absolute;
    width: 100%;
    top: 50%;
  }
}
</style>
